package pubsub;

import java.util.Map;
import java.util.Set;
import java.util.concurrent.CompletableFuture;

public class Publisher {
    private Publisher() {}

    public static void publish(Channel channel, int groupId, int priorityId, String message) {
        Map<Integer, Map<Integer, Set<AbstractSubscriber>>> subscribers = channel.getSubscribers();
        Map<Integer, Set<AbstractSubscriber>> grp = subscribers.get(groupId);
        if (grp != null) {
            int maxPrio = Integer.MIN_VALUE;
            for (Integer prio : grp.keySet()) {
                if (prio > priorityId) {
                    continue;
                }
                maxPrio = Math.max(maxPrio, prio);
            }
            if (maxPrio != Integer.MIN_VALUE) {
                Set<AbstractSubscriber> prio = grp.get(maxPrio);
                for (AbstractSubscriber s : prio) {
                    CompletableFuture.runAsync(() -> s.onMessage(channel.getName(), message));
                }
            }
        }
    }

    public static void publish(String channel, int groupId, int priorityId, String message) {
        publish(Channel.get(channel), groupId, priorityId, message);
    }

    public static void publish(Channel channel, int groupId, String message) {
        publish(channel, groupId, Integer.MAX_VALUE, message);
    }

    public static void publish(String channel, int groupId, String message) {
        publish(Channel.get(channel), groupId, message);
    }

    public static void publish(Channel channel, String message) {
        for (Integer grpId : channel.getSubscribers().keySet()) {
            publish(channel, grpId, message);
        }
    }

    public static void publish(String channel, String message) {
        publish(Channel.get(channel), message);
    }
}
